﻿using System;
using System.Collections.Generic;
using System.IO;
using GeoAPI.Geometries;
using RTools_NTS.Util;

namespace NetTopologySuite.IO
{
	public class WKTFileReader
	{
		private WKTFileReader(WKTReader wktReader)
		{
			this._wktReader = wktReader;
			this.Limit = -1;
		}

		public WKTFileReader(FileInfo file, WKTReader wktReader) : this(wktReader)
		{
			this._file = file;
		}

		public WKTFileReader(string filename, WKTReader wktReader) : this(new FileInfo(filename), wktReader)
		{
		}

		public WKTFileReader(TextReader reader, WKTReader wktReader) : this(wktReader)
		{
			this._reader = reader;
		}

		public int Limit { get; set; }

		public int Offset { get; set; }

		public IList<IGeometry> Read()
		{
			this._count = 0;
			if (this._file != null)
			{
				this._reader = new StreamReader(new BufferedStream(this._file.OpenRead(), 2048));
			}
			IList<IGeometry> result;
			try
			{
				result = this.Read(this._reader);
			}
			finally
			{
				this._reader.Close();
			}
			return result;
		}

		private IList<IGeometry> Read(TextReader bufferedReader)
		{
			IList<IGeometry> list = new List<IGeometry>();
			IEnumerator<Token> enumerator = this._wktReader.Tokenizer(bufferedReader);
			enumerator.MoveNext();
			while (!WKTFileReader.IsAtEndOfTokens(enumerator.Current) && !this.IsAtLimit(list))
			{
				IGeometry item = this._wktReader.ReadGeometryTaggedText(enumerator);
				if (this._count >= this.Offset)
				{
					list.Add(item);
				}
				this._count++;
			}
			return list;
		}

		private bool IsAtLimit(IList<IGeometry> geoms)
		{
			return this.Limit >= 0 && geoms.Count >= this.Limit;
		}

		private static bool IsAtEndOfTokens(Token token)
		{
			return token is EofToken;
		}

		private bool IsAtEndOfFile(StreamReader bufferedReader)
		{
			return bufferedReader.EndOfStream;
		}

		private const int MaxLookahead = 2048;

		private readonly FileInfo _file;

		private TextReader _reader;

		private readonly WKTReader _wktReader;

		private int _count;
	}
}
